#!/bin/bash

echo "================================"
echo "权限系统测试脚本"
echo "================================"
echo ""

# 获取token（假设已经登录）
TOKEN=$(grep -o '"token":"[^"]*' /tmp/login_response.json 2>/dev/null | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "⚠️  未找到登录token，请先登录"
    echo ""
    echo "登录示例："
    echo "curl -X POST http://localhost:8000/api/login/ \\"
    echo "  -H 'Content-Type: application/json' \\"
    echo "  -d '{\"username\":\"admin\",\"password\":\"your_password\"}' \\"
    echo "  > /tmp/login_response.json"
    echo ""
else
    echo "✅ 找到登录token"
    echo ""
fi

echo "测试1: 获取当前用户权限"
echo "--------------------------------"
curl -s -X GET http://localhost:8000/api/current-user-permissions/ \
  -H "Authorization: Token $TOKEN" | python3 -m json.tool
echo ""
echo ""

echo "测试2: 测试主机列表访问（需要 host.view 权限）"
echo "--------------------------------"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
  -X GET http://localhost:8000/api/hosts/ \
  -H "Authorization: Token $TOKEN")

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ 成功访问 (HTTP $HTTP_CODE) - 有权限"
elif [ "$HTTP_CODE" = "403" ]; then
    echo "❌ 访问被拒绝 (HTTP $HTTP_CODE) - 无权限"
else
    echo "⚠️  未知状态 (HTTP $HTTP_CODE)"
fi
echo ""

echo "测试3: 测试用户列表访问（需要 user.view 权限）"
echo "--------------------------------"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
  -X GET http://localhost:8000/api/users/ \
  -H "Authorization: Token $TOKEN")

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ 成功访问 (HTTP $HTTP_CODE) - 有权限"
elif [ "$HTTP_CODE" = "403" ]; then
    echo "❌ 访问被拒绝 (HTTP $HTTP_CODE) - 无权限"
else
    echo "⚠️  未知状态 (HTTP $HTTP_CODE)"
fi
echo ""

echo "================================"
echo "测试完成"
echo "================================"
